package com.atguigu.gmall.product.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.atguigu.gmall.product.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void testLock() {

        // 1. 从redis中获取锁,setnx
        Boolean lock = this.stringRedisTemplate.opsForValue().setIfAbsent("lock", "ok");
        if (lock) {
            String value = stringRedisTemplate.opsForValue().get("num");

            // 没有该值return
            if (StringUtils.isBlank(value)) {
                return;
            }
            // 有值就转成成int
            int num = Integer.parseInt(value);
            // 把redis中的num值+1
            this.stringRedisTemplate.opsForValue().set("num", String.valueOf(++num));

        }else {
            // 3. 每隔1秒钟回调一次，再次尝试获取锁
            try {
                Thread.sleep(100);
                testLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }



    }



}

